<template>
  <div class="page qrCodeList">
    <StoreChoice
      ref="StoreChoice"
      :isReset="true"
      :current="[]"
      :multipleChoice="false"
      @listenToStoreSelect="getSelectStoreValue"
      :statusFilter="false"
      :hasTotal="true"
      :stylewidth="true"
    
    />
    <div class="scroll-view">
      <template v-if="$route.query.codeType">
        <customHeader middleTitle="支付宝门店码" @leftCallBack="handleBack"/>
      </template>
      <template v-else>
        <customHeader
          v-if="authAdd"
          middleTitle="收款二维码"
          @leftCallBack="handleBack"
          @rightCallBack="add"
          @rightCallBack2="scan"
        >
          <i class="zhk-list-create"></i>
          <div slot="slot2" v-if="authScan">
            <i class="zhk-sm"></i>
          </div>
        </customHeader>
        <customHeader
        v-else
          middleTitle="收款二维码"
          @leftCallBack="handleBack"
          @rightCallBack2="scan"
        >
          <div slot="slot2" v-if="authScan">
            <i class="zhk-sm"></i>
          </div>
        </customHeader>
      </template>
      <div class="page-body" v-if="$route.query.codeType">
        <div class="shop-name">{{shopName}}</div>
        <ul class="qrCode-list">
          <li>
            <div class="info" @click="linkTo({composeQrCodeUrl: storeCodeImg}, '支付宝门店码')">
              <div class="left store">
                <div class="logo"><img :src="storeCodeImg"></div>
              </div>
              <div class="right">
                <div class="name">支付宝门店码</div>
              </div>
            </div>
            <div class="ope-list">
              <div @click="saveImg(storeCodeImg)">保存到手机</div>
            </div>
          </li>
        </ul>
      </div>
      <div class="page-body" v-else>
        <div class="shop-name">{{shopName}}</div>
        <no-data msg="暂无数据" v-if="list.length==0"></no-data>
        <ul
          class="qrCode-list"
          v-infinite-scroll="loadMore"
          infinite-scroll-disabled="loading"
          infinite-scroll-distance="30"
          v-if="list.length>0"
        >
          <li :key="index" v-for="(item,index) in list">
            <div class="info" @click="linkTo(item)">
              <div class="left">
                <div class="logo">
                  <div class="type" :class="{miniApp:item.qrcodeType==2}">{{qrcodeTypeFormate(item.qrcodeType)}}</div>
                </div>
              </div>
              <div class="right">
                <div class="name">{{item.qrcodeName||"收款码1(默认)"}}</div>
                <div class="codeId" v-if="item.qrcodeId">码ID：{{item.qrcodeId}}</div>
                <div class="cashier" v-if="item.cashierName">收银员：{{item.cashierName}}</div>
                <div v-if="item.isOpenAmount==1">
                  <div class="cashier" v-if="item.shopQrcodeAmountCount>1">固定金额：已设置{{item.shopQrcodeAmountCount}}个</div>
                  <div class="cashier" v-if="item.shopQrcodeAmountCount==1">固定金额：{{item.shopQrcodeAmount.payAmount}}元</div>
                  <div class="cashier" v-if="item.shopQrcodeAmountCount==1">收款内容：{{item.shopQrcodeAmount.payContent}}</div>
                </div>
              </div>
            </div>
            <div class="ope-list" v-if="item.qrcodeType != 4">
              <div @click="saveImg(item.composeQrCodeUrl)">下载</div>
              <div v-if="!item.qrcodeId||!authEdit" :class="{disabled:!item.qrcodeId||!authEdit}">编辑</div>
              <div v-else @click="toEdit(item)">编辑</div>
            </div>
            <div class="ope-list" v-if="item.qrcodeType == 4">
              <div @click="saveImg(item.composeQrCodeUrl)" v-if="item.composeQrCodeUrl">下载</div>
              <div @click="getCode(item)" v-else>获取数币码牌</div>
            </div>
          </li>
        </ul>
        <p v-show="loading" class="page-infinite-loading">
          <mt-spinner :style="{display:'inline-block'}" type="fading-circle"></mt-spinner>
        </p>
      </div>
    </div>
  </div>
</template>

<script>
import Vue from "vue";
import jsAuthority from "../../tools/jsAuthority.js";
import customHeader from "../../components/header/header";
import { Toast, MessageBox } from "mint-ui";
import jsBridge from "../../tools/jsBridge";
import noData from "../../components/noData/noData";
import StoreChoice from "../../components/StoreChoice/StoreChoice";
export default {
  name: "qrCodeList",
  data() {
    return {
      storeCodeImg: null,
      authAdd:false,
      authEdit:false,
      authScan:false,
      openState: 0,
      OpenMiniStatus: false,//门店是否开启小程序
      list: [],
      loading: false,
      noMore: false,
      totalCount: 0,
      pageIndex: 1,
      pageIndex1: 1,
      pageSize: 10,
      shopId: ""
    };
  },
  methods: {
    
    getSelectStoreValue(value,name){
      console.log(value,name);
      this.shopName=name
      this.shopId=value[0].selectKey
      this.loadDatas()
      if (typeof window !== 'undefined') {
    // 在浏览器环境中运行的代码
    console.log(window.location.hostname)
}
    },
    qrcodeTypeFormate(qrcodeType) {
      let qt = "未知";
      if (qrcodeType === 0 || qrcodeType === 1 || qrcodeType === 3) {
        qt = "基础码";
      }
      else if (qrcodeType === 2) {
        qt = "小程序码";
      }
      return qt;
    },
    handleBack() {
      MessageBox.close(false);
      this.$router.back();
    },
    getCode(){
      this.ajax({
        url: `/newapp/code/getDigitalCurrencyQrCode.do?shopId=${this.shopId}`,
        type: "get",
        controlLoading: true
      })
        .then(res => {
          console.log(res,"89");
          if (res.success) {
            this.pageIndex = 1;
            this.loadData();
          } else {
            Toast(res.msg);
          }
        })
        .catch((err) => {
        });
    },
    add() {
      this.$router.push({
        path: "/storeManage/getMoneyQrCode/editQrCode",
        query: { type: 0, shopId: this.shopId, shopName: this.shopName }
      });
    },
    toEdit(info) {
      if (!this.OpenMiniStatus && info.qrcodeType === 2) {
        Toast('门店开启小程序后才能进行编辑');
        return;
      }
      this.$router.push({
        path: "/storeManage/getMoneyQrCode/editQrCode",
        query: { info: info, type: 1, shopId: this.shopId, shopName: this.shopName }
      });
    },
    //保存图片
    saveImg(imgUrl) {
      try {
        jsBridge.savePicture({ url: imgUrl }, function (response) {
          if (
            response &&
            (response.success === true || response.success === "true")
          ) {
            Toast("保存成功");
          } else {
            Toast("保存失败");
          }
        });
      } catch (e) {
        Toast("保存异常");
      }
    },
    //扫码绑定
    scan() {
      if(!this.authScan){
        return;
      }
      const _this = this;
      try {
        jsBridge.scanQRCode(
          {
            type: "bar",
            title: "扫描绑定二维码",
            text: "请将取景器对准未绑定的二维码"
          },
          function (response) {
            if (
              response &&
              (response.success === true || response.success === "true")
            ) {
              let code = response.resultObject;
              //判断二维码是否正确
              const decollator = "?c=";
              if (code && code.indexOf(decollator) > 0) {
                let qrcodeType=2;
                if(code.indexOf("p.do") > 0){
                  qrcodeType=1;
                }
                code = code.substring(
                  code.indexOf(decollator) + decollator.length
                );
                _this.scanCallback(code,qrcodeType);
              } else {
                Toast("二维码错误，请重新扫码");
              }
            } else if (response && response.code && response.code == "-10") {
              //未扫码，返回，不处理
            } else if (response && response.code && response.code == "11") {
              Toast(response.msg);
            } else {
              Toast("扫码失败");
            }
          }
        );
      } catch (err) {
        Toast("扫码异常");
      }
    },
    scanCallback(data,qrcodeType) {
      const shopId = this.shopId;
      this.ajax({
        url: `/newapp/code/scanCode.do?shopId=${shopId}&qrcodeId=${data}&qrcodeType=${qrcodeType}`,
        type: "get",
        controlLoading: true
      })
        .then(res => {
          if (res && String(res.success) == "true") {
            let info = {
              shopId: shopId,
              qrcodeId: data,
              qrcodeName: "",
              qrcodeType: qrcodeType,
            };
            //res.code -1 表示 二维码已被绑定; 为 2 表示 基础码 已开通小程序 请绑定小程序收款码; 为 3时 表示 基础码 未 开通小程序 ; 为 4 时表示 小程序码 已开通小程序; 为 5 时表示 小程序码未开通小程序 , 请绑定 基础二维码;
            if (res.code === 2) {
              //Toast('该门店已开通小程序，请绑定小程序收款码');
              this.$router.push({
                path: "/storeManage/getMoneyQrCode/editQrCode",
                query: { type: 1, shopId: shopId, info: info,title:"新增收款码" }
              });
            } else if (res.code === 3) {
              this.$router.push({
                path: "/storeManage/getMoneyQrCode/editQrCode",
                query: { type: 1, shopId: shopId, info: info,title:"新增收款码" }
              });
            } else if (res.code === 4) {
              this.$router.push({
                path: "/storeManage/getMoneyQrCode/editQrCode",
                query: { type: 1, shopId: shopId, info: info,title:"新增收款码" }
              });
            } else if (res.code === 5) {
              Toast('该门店未开通小程序，请绑定基础二维码');
            }
          } else {
            Toast(res.msg);
          }
        })
        .catch((err) => {

        });
    },
    //查看收款二维码
    linkTo(item, title) {
      const code = item.qrcodeId;
      const imgUrl = item.composeQrCodeUrl;
      const openState = this.openState;
      const shopId = this.shopId;
      if (openState && openState === 3) {
        //去查看二维码
        this.$router.push({
          path: "/storeManage/getMoneyQrCode/qrCodeDetail",
          query: { code: code, shopId: shopId, imgUrl: imgUrl, title: title }
        });
      } else {
        if (openState && openState == 2) {
          //禁用收款帐号
          MessageBox({
            title: "提示",
            message: "该门店暂未开通收款账户，开通后收款码才能正常收款。",
            confirmButtonText: "确定"
          }).then(action => {
            //去查看二维码
            this.$router.push({
              path: "/storeManage/getMoneyQrCode/qrCodeDetail",
              query: { code: code, shopId: shopId, imgUrl: imgUrl }
            });
          });
        } else {
          MessageBox({
            title: "提示",
            message: "该门店暂未开通收款账户，开通后收款码才能正常收款。",
            confirmButtonText: "知道了"
          }).then(action => {
            //去查看二维码
            this.$router.push({
              path: "/storeManage/getMoneyQrCode/qrCodeDetail",
              query: { code: code, shopId: shopId, imgUrl: imgUrl }
            });
          });
        }
      }
    },
    //无限加载
    loadMore() {
      if (this.loading || this.noMore) {
        return;
      }
      this.loadData();
    },
    //查询门店开通小程序状态
    getOpenMiniStatus(callBack) {
      //serviceCode 服务状态： 1_0：未开通； 1_1：待开通微信收款； 1_2：收款码待激活； 1_3：已开通
      this.ajax({
        url: `/applet/manager/queryHasOpenedYzProShop.do?shopId=${this.shopId}&serviceCode=9&serviceStatus=1_3`,
        type: "get",
        controlLoading: false
      })
        .then(response => {
        
          callBack && callBack();
          if (response && response.success) {
            const data = response.resultObject;
            if (data && data.length > 0) {
              this.OpenMiniStatus = true;
            } else {
              this.OpenMiniStatus = false;
            }
          } else {
            Toast(response.msg);
          }
        })
        .catch((err) => {
          callBack && callBack();
        });
    },
    //加载二维码列表
    loadData() {
      this.loading = true;
      if (this.pageIndex == 1) {
        this.list = [];
      }
      console.log(this.shopId,this.pageIndex,this.pageSize,'shop');
      this.ajax({
        url: `/newapp/code/list.do?shopId=${this.shopId}&currentPage=${this.pageIndex}&pageSize=${this.pageSize}`,
        type: "get",
        controlLoading: true
      })
        .then(res => {
          this.loading = false;
         
          if (res.success) {
            const data = res.resultObject;
            if (data != null && JSON.stringify(data) != "{}") {
              this.list = this.list.concat(data.dataList);
              console.log(this.list,"678");
              if (data.dataAllCount) {
                this.noMore = Math.ceil(data.dataAllCount / this.pageSize) === this.pageIndex ? true : false;
              } else {
                this.noMore = true;
              }
              this.pageIndex = this.pageIndex + 1;
            } else {
              this.noMore = true;
            }
          }
        })
        .catch((err) => {
          this.loading = false;
          this.noMore = true;
        });
    },

    //入口是我的页面下面的收款二维码     
    loadDatas() {
      this.loading = true;
      // if (this.pageIndex == 1) {
      //   this.list = [];
      // }
      console.log(this.shopId,this.pageIndex,this.pageSize,'shop');
      this.ajax({
        url: `/newapp/code/list.do?shopId=${this.shopId}&currentPage=${this.pageIndex1}&pageSize=${this.pageSize}`,
        type: "get",
        controlLoading: true
      })
        .then(res => {
          this.loading = false;
         
          if (res.success) {
            const data = res.resultObject;
            if (data != null && JSON.stringify(data) != "{}") {
              this.list = this.list.concat(data.dataList);
              console.log(this.list,"678");
              if (data.dataAllCount) {
                this.noMore = Math.ceil(data.dataAllCount / this.pageSize) === this.pageIndex1 ? true : false;
              } else {
                this.noMore = true;
              }
              this.pageIndex1 = this.pageIndex1 + 1;
            } else {
              this.noMore = true;
            }
          }
        })
        .catch((err) => {
          this.loading = false;
          this.noMore = true;
        });
    },
    //获取门店详情验证是否开通收款帐户
    initOpenState(shopId) {
      this.ajax({
        url: "/app/shop/getShopDetail.do?shopId=" + shopId,
        type: "get"
      })
        .then(res => {
       
          if (res.success) {
            var data = res.resultObject;
            if (data != null && JSON.stringify(data) != "{}") {
              let openState = 0;
            
              if (
                data.wxPayStatus == null ||
                data.wxPayStatus == 0 ||
                data.wxPayStatus == 5 ||
                data.wxPayStatus == 6
              ) {
                ////开通收款账户
                openState = 1;
              } else if (data.wxPayStatus == 3 || data.wxPayStatus == 4) {
                //禁用收款账户管理
                openState = 2;
              } else {
                //跳转收款账户管理
                openState = 3;
              }
              this.openState = openState;
            }
          }
        })
        .catch((err) => {

        });
    },
    getAuth(){
      jsAuthority.checkedSuccess(() => {
        this.authAdd = jsAuthority.checked(
          "app.shop.gather_qrcode.add"
        );
      });
      jsAuthority.checkedSuccess(() => {
        this.authEdit = jsAuthority.checked(
          "app.shop.gather_qrcode.edit"
        );
      });
      jsAuthority.checkedSuccess(() => {
        this.authScan = jsAuthority.checked(
          "app.shop.gather_qrcode.bind"
        );
      });
    }
  },
  created() {
    const shopId = this.$route.query.shopId;
    this.shopName = this.$route.query.shopName;
    this.shopId = shopId;
    if(this.$route.query.codeType) {
      this.openState = 3;
      this.storeCodeImg = (!/cross-bm/i.test(navigator.userAgent) ? '' : window.APP.serverUrl)+`/newapp/shop/getQrCodeImage_${this.$route.query.supplierId}_${this.$route.query.shopId}_${this.$route.query.codeType}.jpg`;
      return;
    }
    

    this.getAuth();
    this.getOpenMiniStatus(this.loadData);
    this.initOpenState(shopId);
  },
  mounted(){
    if(!this.$route.query.shopId&&!this.$route.query.shopName){
      this.$refs.StoreChoice.popupShow();
  
    
    }
  },
  components: {
    customHeader,
    noData,
    StoreChoice
  }
};
</script>

<style lang='scss' scoped>
@import "getMoneyQrCode";
.qrCodeList .qrCode-list li .info .left.store .logo {
  background: none;
  text-align: center;
  img {
    height: 98%;
    width: auto;
  }
}
</style>